from django.shortcuts import render, redirect, reverse, HttpResponse
from chart_web.form import crab_love_form
from django.http import JsonResponse
from chart_web import models
from uuid import uuid4
from utils import Md5
import datetime
from utils.pagination import Pagination


def crab_love(request):
    '''螃蟹界面预览'''
    if request.method == 'GET':
        # 如果是get请求，查询当前所有的螃蟹文章，进行渲染(一页12个)
        # 获取所有的文章
        queryset = models.NeverLoveMe.objects.filter(is_delete=False)
        page_object = Pagination(
            current_page=request.GET.get('page'),
            all_count=queryset.count(),
            base_url=request.path_info,
            query_params=request.GET,
            per_page=10,
        )
        never_love_me = queryset[page_object.start:page_object.end]
        page_html = page_object.page_html()
    return render(request, 'crab_love.html', locals())


def crab_love_add(request, username):
    '''螃蟹文章添加 前端页面待修改'''
    # 如果是get请求，渲染添加页面
    if request.method == 'GET':
        form = crab_love_form.crab_add(request)
        return render(request, 'love_md.html', locals())
    # form 校验
    form = crab_love_form.crab_add(request, data=request.POST)
    if form.is_valid():
        # 通过保存
        form.instance.userinfo = request.chart_web.user
        instance = form.save()
        return redirect('crab_love')
    # 不通过返回错误信息
    return render(request, 'love_md.html', locals())


def crab_article(request, pk):
    '''文章详细页面/评论渲染 前端页面待修改'''
    # 根据传过来的pk查询当前文章，进行渲染
    if request.method == 'GET':
        # 螃蟹文章详细渲染
        article_obj = models.NeverLoveMe.objects.filter(pk=pk, is_delete=False).first()
        return render(request, 'crab_article.html', locals())
